package com.xjm.ips.service;

import com.xjm.ips.entity.MyPage;
import com.xjm.ips.entity.SettleSalary;
import com.xjm.ips.entity.SettleTax;
import com.xjm.ips.mapper.SettleSalaryMapper;
import com.xjm.ips.utils.SalaryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class SettleSalaryService {
    @Autowired
    SettleSalaryMapper settleSalaryMapper;

    public MyPage getAllSettleSalariesForSearch(Integer pageNo, Integer pageSize,SettleSalary settleSalary){
        if(pageNo!=null && pageSize!=null){
            pageNo = (pageNo-1)*pageSize;
        }
        List<SettleSalary> data = settleSalaryMapper.getAllSettleSalariesForSearch(pageNo,pageSize,settleSalary);
        Long total = settleSalaryMapper.getTotalForSearch(settleSalary);
        MyPage myPage = new MyPage();
        myPage.setData(data);
        myPage.setTotal(total);
        return myPage;
    }

    @Transactional
    public Integer addMonthSalaries(List<SettleSalary> settleSalaryList) {
        for (SettleSalary settleSalary : settleSalaryList) {
            SettleTax sumTax = settleSalaryMapper.getSumSettleData(settleSalary.getJobNo());
            SettleTax settleTax = SalaryUtils.calcMonthSalary(settleSalary,sumTax.getActrualTaxSalary(),sumTax.getTaxMoney());
            settleSalary.setId(null);
            settleSalary.setActrualTaxSalary(settleTax.getActrualTaxSalary());
            settleSalary.setTaxMoney(settleTax.getTaxMoney());
            settleSalary.setActualIncome(settleTax.getActualIncome());
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            int last = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, last);
            settleSalary.setCreateDate(cal.getTime());
            settleSalaryMapper.insertSelective(settleSalary);
        }
        return settleSalaryList.size();
    }


    public MyPage getAllSettleSalaries(Integer pageNo, Integer pageSize,SettleSalary settleSalary){
        if(pageNo!=null && pageSize!=null){
            pageNo = (pageNo-1)*pageSize;
        }
        List<SettleSalary> data = settleSalaryMapper.getAllSettleSalaries(pageNo,pageSize,settleSalary);
        Long total = settleSalaryMapper.getTotal(settleSalary);
        MyPage myPage = new MyPage();
        myPage.setData(data);
        myPage.setTotal(total);
        return myPage;
    }

    public Integer deleteSalaryMonthById(Integer id) {
        return settleSalaryMapper.deleteByPrimaryKey(id);
    }
}
